package com.zangchat.service.impl;

import com.alibaba.fastjson.JSON;
import com.common.core.domain.AjaxResult;
import com.common.utils.StringUtils;
import com.zangchat.domain.ChatUsers;
import com.zangchat.domain.ChatUsersDTO;
import com.zangchat.service.NearBySearchService;
import com.zangchat.utils.SessionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.*;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 附近人实现类
 * @author liuduan
 */
@Service
public class NearBySearchServiceImpl implements NearBySearchService {

    @Autowired
    private RedisTemplate redisTemplate;

    //GEO相关命令用到的KEY
    private final static String KEY = "user_info";

    /**
     * 将经纬度储存到缓存
     * @param
     * @return
     */
    @Override
    public AjaxResult save(Long userId,double longitude,double latitude) {
        String sessionId = SessionUtils.getSessionId();
        if (StringUtils.isNull(sessionId)){
            return AjaxResult.notLogin();
        }

        Long flag = redisTemplate.opsForGeo().add(KEY, new RedisGeoCommands.GeoLocation<>(
                userId+"",
                new Point(longitude, latitude))
        );
        if (flag != null && flag > 0){
            return AjaxResult.success("成功");
        }else {
            Long remove = redisTemplate.opsForGeo().remove(KEY,userId+"");
            if (remove>0){
                Long flags = redisTemplate.opsForGeo().add(KEY, new RedisGeoCommands.GeoLocation<>(
                        userId+"",
                        new Point(longitude,latitude))
                );
                if (flags != null && flags > 0){
                    return AjaxResult.success("成功");
                }
            }
        }
        return AjaxResult.error("失败");
    }

    /**
     * 根据当前位置获取附近指定范围内的用户
     * @param distance 指定范围 单位km ，可根据{@link org.springframework.data.geo.Metrics} 进行设置
     * @param userLng 用户经度
     * @param userLat 用户纬度
     * @return
     */
    @Override
    public AjaxResult nearBySearch(double distance, double userLng, double userLat) {
        List<ChatUsers> users = new ArrayList<>();
        // 1.GEORADIUS获取附近范围内的信息
        GeoResults<RedisGeoCommands.GeoLocation<Object>> reslut =
                redisTemplate.opsForGeo().radius(KEY,
                        new Circle(new Point(userLng, userLat), new Distance(distance, Metrics.KILOMETERS)),
                        RedisGeoCommands.GeoRadiusCommandArgs.newGeoRadiusArgs()
                                .includeDistance()
                                .includeCoordinates().sortAscending());
        //2.收集信息，存入list
        List<GeoResult<RedisGeoCommands.GeoLocation<Object>>> content = reslut.getContent();
        //3.过滤掉超过距离的数据
        content.forEach(a-> users.add(
                new ChatUsersDTO().setDistance(a.getDistance().getValue())
                        .setLatitude(a.getContent().getPoint().getX())
                        .setLongitude(a.getContent().getPoint().getY())));
        return AjaxResult.success("成功",users);
    }

}
